package com.zm.study.common;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Created by Administrator on 2018/5/13.
 */
public class ZipFileUtil {
    /**
     * 压缩文件
     * @param filePath
     * @param zipfile
     * @throws IOException
     */
    public static void fileChangeZip(String filePath, java.io.File zipfile) throws IOException {
        File srcfile[] = new File(filePath).listFiles();
        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipfile));
        for(int i = 0; i < srcfile.length; ++i){
            if(srcfile[i].isDirectory()){
                zipDir(zipOut,srcfile[i],srcfile[i].getName());
            }else{
                zipFile(zipOut,srcfile[i],null);
            }
        }
        zipOut.close();
    }


    /**
     * 递归压缩文件夹
     * @param zipOut  生成zip路径
     * @param dirFile 被压缩文件夹
     * @param fileName 目的就是为了维持原来的目录
     * @return
     */
    private static ZipOutputStream zipDir(ZipOutputStream zipOut, File dirFile, String fileName) throws IOException {
        File fileList[] = dirFile.listFiles();
        for(int i = 0;i < fileList.length;i++){
            if(fileList[i].isDirectory()){
                zipDir(zipOut,fileList[i],fileName + File.separator + fileList[i].getName());
            }else{
                zipFile(zipOut,fileList[i],fileName);
            }
        }
        return zipOut;
    }

    /**
     * 压缩单个文件
     * @param zipOut
     * @param file
     * @param fileName
     * @throws IOException
     */
    private static void zipFile(ZipOutputStream zipOut, File file, String fileName) throws IOException {
        InputStream input = null;
        byte[] buf = new byte[1024];
        input = new FileInputStream(file);
        if(fileName != null){
            zipOut.putNextEntry(new ZipEntry(fileName + File.separator + file.getName()));
        }else{
            zipOut.putNextEntry(new ZipEntry(file.getName()));
        }
        int temp = 0;
        while((temp = input.read(buf)) != -1){
            zipOut.write(buf,0,temp);
        }
        input.close();
    }
}
